package com.example.mytestdemo.softkey

import android.animation.ValueAnimator
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import androidx.core.view.*
import com.example.mytestdemo.BaseViewBindActivity
import com.example.mytestdemo.R
import com.example.mytestdemo.databinding.ActivitySoftkeyLayoutBinding
import com.example.mytestdemo.utils.KeyboardUtils
import com.example.mytestdemo.utils.ScreenUtils

/**
 *计算软键盘高度位置
 */
class SoftKeyActivity : BaseViewBindActivity<ActivitySoftkeyLayoutBinding>() {

    private lateinit var mDragMoveHelper: DragMoveHelper;
    private var mIsSoftKeyBoard = false
    private var mScreenWidth = 0
    private var mScreenHeight = 0
    private  lateinit var   mFrameLayoutParams: FrameLayout.LayoutParams
    private var mLastBottomMargin = 0
    private var mContainLastX = 1F
    private var mContainLastY = 1F
    private var mSoftKeyHeight = 0F

    private lateinit var valueAnimator2: ValueAnimator

    override fun onCreate(savedInstanceState: Bundle?) {
        //非常重要，没有这句话监听无法生效
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.R) {
            window.setDecorFitsSystemWindows(false)
        }
        super.onCreate(savedInstanceState)
    }

    override fun getLayoutInflateId(): Int {
      return R.layout.activity_softkey_layout
    }

    override fun initData() {
        setSoftKeyBoardListener()
    }

    override fun initUI() {
        mScreenWidth = ScreenUtils.getScreenWidth(this)
        mScreenHeight = ScreenUtils.getScreenHeight(this)
        mFrameLayoutParams = FrameLayout.LayoutParams(
            500,
            FrameLayout.LayoutParams.WRAP_CONTENT
        )
        mFrameLayoutParams.gravity = Gravity.BOTTOM or Gravity.END
        mFrameLayoutParams.bottomMargin = 120
        mFrameLayoutParams.rightMargin = 20
        mLastBottomMargin = mFrameLayoutParams.bottomMargin
        mBind.llContain.setLayoutParams(mFrameLayoutParams)

        mDragMoveHelper = DragMoveHelper(mBind.llContain,mBind.clParent);
        mDragMoveHelper.bind()

        mBind.llContain.post {
//            mBind.clParent.x = -800f
//            mBind.clParent.y = -1500f
//            mContainLastX =  mBind.clParent.getX();
//            mContainLastY =  mBind.clParent.getY();
            Log.d(
                "tgww",
                "initlization mScreenWidth:" +mScreenWidth + "mScreenHeight:" + mScreenHeight)

            Log.d("tgww", "初始化viewLeft:${mBind.clParent.left}---viewRight:${mBind.clParent.right}---viewTop:${mBind.clParent.top}----viewBottom:${mBind.clParent.bottom}")
            Log.d("tgww", "margin初始化vviewLeft:${mBind.clParent.marginLeft}---viewRight:${mBind.clParent.marginRight}---viewTop:${mBind.clParent.marginTop}----viewBottom:${mBind.clParent.marginBottom}")
            Log.d("tgw move", "changePosition 初始化 moveView: " + mBind.clParent.getX() + "----y:" + mBind.clParent.getY())
        }

//        initSoftkeyAnima()
    }


    private fun setSoftKeyBoardListener() {
        SoftKeyBoardListener.setListener(
            this.window,
            object : SoftKeyBoardListener.OnSoftKeyBoardChangeListener {
                override fun keyBoardShow(height: Int) {
                    mIsSoftKeyBoard = true
                    changePosition(height)
                }

                override fun keyBoardHide(height: Int) {
                    mIsSoftKeyBoard = false
                    if (mContainLastX!=1f&&mContainLastY!=1f){
                        mBind.clParent.x = mContainLastX
                        mBind.clParent.y =mContainLastY
                        mContainLastX = 1f;
                        mContainLastY = 1f;
                    }

//                    mFrameLayoutParams.bottomMargin = mLastBottomMargin
//                    mBind.clParent.setLayoutParams(mFrameLayoutParams)

                    Log.d("tgww", "去设置后viewLeft:${mBind.clParent.left}---viewRight:${mBind.clParent.right}---viewTop:${mBind.clParent.top}----viewBottom:${mBind.clParent.bottom}")
                    Log.d("tgww", "margin去设置后viewLeft:${mBind.clParent.marginLeft}---viewRight:${mBind.clParent.marginRight}---viewTop:${mBind.clParent.marginTop}----viewBottom:${mBind.clParent.marginBottom}")
                    Log.d("tgww", "设置后控后位置xy：${mBind.clParent.x}---控件y：${mBind.clParent.y}")

                }
            })
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        getCurrentFocus()?.let { KeyboardUtils.hideKeyboard(it) }

        return super.dispatchTouchEvent(ev)

    }
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return super.onTouchEvent(event)
    }


    /**
     * 软键盘弹出时设置弹框位置
     *
     * @param height 软键盘高度
     */
    fun changePosition(height: Int) {
        Log.d("tgw move", "changePosition moveView: " + mBind.clParent.getX() + "----y:" + mBind.clParent.getY())
//        var isHas = false
//        val service: IStudentQuickAskMainService = ARouter.getInstance().navigation(
//            IStudentQuickAskMainService::class.java
//        )
//        if (service != null) {
//            isHas = QuickAskFactory.phoneHasNav(service.getTopActivity())
//        }
//        var bottom: Int
//        if (service != null && service.isThreeDriver()) { //3代
//            bottom =450
//        } else if (service != null && service.isFourFiveDriver()) { //4,5代
//            bottom = 420
//            if (!isHas) {
//                bottom = getContext().getResources().getDimension(R.dimen.dimen_370dp)
//            }
//        } else {
//            bottom = height
//        }
//        mSoftKeyHeight = height.toFloat();
        var bottom = height

        Log.d("tgww", "键盘弹起变化后viewLeft:${mBind.clParent.left}---viewRight:${mBind.clParent.right}---viewTop:${mBind.clParent.top}----viewBottom:${mBind.clParent.bottom}")
        Log.d("tgww", "键盘弹起变化marginvviewLeft:${mBind.clParent.marginLeft}---viewRight:${mBind.clParent.marginRight}---viewTop:${mBind.clParent.marginTop}----viewBottom:${mBind.clParent.marginBottom}")

        Log.d("tgww", "控件高度：${mBind.clParent.height}---控件宽度：${mBind.clParent.width}")

        Log.d("tgww", "控件高度xy：${mBind.clParent.x}---控件y：${mBind.clParent.y}")

        val moveY: Float =Math.abs(mBind.clParent.y)
        val moveX: Float =Math.abs(mBind.clParent.x)
        Log.d("tgww", "软键盘高度：${height}---控件底部距离：${moveY}")

        mFrameLayoutParams.gravity = Gravity.BOTTOM or Gravity.END
        if (moveY <= bottom) {
            Log.d("tgww", "小于 去设置")
//            mLastBottomMargin = mFrameLayoutParams.bottomMargin;
//            mFrameLayoutParams.bottomMargin = bottom;
//            mContainerView.setLayoutParams(mFrameLayoutParams);

//            val viewLeft: Int = mBind.clParent.getLeft()
//            val viewTop: Int = mBind.clParent.getTop() - bottom
//            val viewRight: Int = mBind.clParent.getRight()
//            val viewBottom: Int = mBind.clParent.getBottom()-bottom

            val viewLeft: Float = mBind.clParent.getLeft()-moveX;
            val viewTop: Int = mBind.clParent.getTop() - bottom
            val viewRight: Int = mBind.clParent.getRight()
            val viewBottom: Int = bottom

//            mBind.clParent.x = viewLeft.toFloat()
//            mBind.clParent.y = viewTop.toFloat()

            Log.d("tgww", "去设置viewLeft:$viewLeft---viewRight:$viewRight---viewTop:$viewTop----viewBottom:$viewBottom")
//            mFrameLayoutParams.setMargins(viewLeft, viewTop, viewRight, viewBottom)
//            mFrameLayoutParams.leftMargin = viewLeft;
//            mFrameLayoutParams.rightMargin = viewRight;
//            mFrameLayoutParams.topMargin = viewTop;
//            mFrameLayoutParams.bottomMargin = viewBottom;
//            mBind.clParent.setLayoutParams(mFrameLayoutParams)

            mContainLastX =   mBind.clParent.x
            mContainLastY =   mBind.clParent.y
            mBind.clParent.layout(viewLeft.toInt(), viewTop, viewRight, viewBottom)

            mBind.clParent.y = -viewBottom.toFloat();
            mBind.clParent.x = viewLeft.toFloat();
            valueAnimator2 = ValueAnimator.ofFloat(mContainLastY, -viewBottom.toFloat());
            valueAnimator2.addUpdateListener { animation ->
                val curValue = animation.animatedValue as Float
                Log.d("tgww", "动画：${curValue}---控件y：${  mBind.clParent.y}")


                mBind.clParent.y = curValue;
                Log.d("tgww", "动画去设置后viewLeft:${mBind.clParent.left}---viewRight:${mBind.clParent.right}---viewTop:${mBind.clParent.top}----viewBottom:${mBind.clParent.bottom}")
                Log.d("tgww", "动画去设置后控件高度xy：${mBind.clParent.x}---控件y：${mBind.clParent.y}")

            }
            valueAnimator2.duration = 3000
//            valueAnimator2.start()
            Log.d("tgww", "去设置后viewLeft:${mBind.clParent.left}---viewRight:${mBind.clParent.right}---viewTop:${mBind.clParent.top}----viewBottom:${mBind.clParent.bottom}")
            Log.d("tgww", "margin去设置后viewLeft:${mBind.clParent.marginLeft}---viewRight:${mBind.clParent.marginRight}---viewTop:${mBind.clParent.marginTop}----viewBottom:${mBind.clParent.marginBottom}")
            Log.d("tgww", "设置后控件高度xy：${mBind.clParent.x}---控件y：${mBind.clParent.y}")

//            mBind.clParent.layout(viewLeft, viewTop, viewRight, viewBottom)

        }
    }



    private fun initSoftkeyAnima(){
        //非常重要，没有这句话监听无法生效
//        window.setDecorFitsSystemWindows(false)

        //android 11
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.R) {
            var startBottom = 0
            var endBottom = 0


            val cb = object : WindowInsetsAnimation.Callback(WindowInsets.Type.ime()),OnApplyWindowInsetsListener {


                override fun onPrepare(animation: WindowInsetsAnimation) {
                    var animationCusTom :WindowInsetsAnimation = WindowInsetsAnimation(WindowInsets.Type.ime(),LinearInterpolator(),5000)

                    super.onPrepare(animationCusTom)
                    // #1: 第一，onPrepare 被调用会允许应用记录当前布局的任何状态
//                    startBottom = mBind.edit.calculateBottomInWindow()
                    Log.d(TAG, "initSoftkeyAnima onPrepare: ${animationCusTom.durationMillis}")

//                    // 从起始位置到结束位置，我们利用线性插值的方式和动画本身的分数
//                    // 来计算视图的偏移量。
//                    val offset = AnimationUtils.lerp(
//                        startBottom - endBottom,
//                        0,
//                        animation.interpolatedFraction
//                    )
//                    // … 然后我们再用 translationY 来设置
//                    mBind.edit.translationY = offset

                }


                // #2: 在 onPrepare 之后，正常的 WindowInsets 会被下发到视图层次
                // 结构中，它包含了结束状态。这意味着您的视图的
                // OnApplyWindowInsetsListener 会被调用，这会导致一个布局传递
                // 以反映结束状态


                override fun onStart(
                    animation: WindowInsetsAnimation,
                    bounds: WindowInsetsAnimation.Bounds
                ): WindowInsetsAnimation.Bounds {
                    mSoftKeyHeight = Math.abs((bounds.lowerBound.top-bounds.upperBound.bottom).toFloat())
                    // #3: 接下来是 onStart ，这个会在动画开始的时候被调用。
                    // 这允许应用记录下视图的目标状态或者结束状态
                    var animationCusTom :WindowInsetsAnimation = WindowInsetsAnimation(WindowInsets.Type.ime(),LinearInterpolator(),5000)

                    Log.d(TAG, "initSoftkeyAnima动画时长:${animation.durationMillis}")
                    Log.d(TAG, "initSoftkeyAnima 键盘高度onStart:$mSoftKeyHeight")
                    Log.d(TAG, "initSoftkeyAnima onStart:${bounds.lowerBound} ----${bounds.upperBound}")
                    return super.onStart(animationCusTom, WindowInsetsAnimation.Bounds(
                        android.graphics.Insets.of(
                            0,
                            0,
                            0,
                            0
                        )
                    ,  android.graphics.Insets.of(
                            0,
                            0,
                            0,
                            0
                        )))
                }


                override fun onProgress(
                    insets: WindowInsets,
                    runningAnimations: List<WindowInsetsAnimation>
                ): WindowInsets {


                    // #4: 接下来是一个很重要的调用：onProgress 。这个会在动画中每次视窗属性
                    // 更改的时候被调用。在软键盘的这个例子中，这个调用会发生在软键盘在屏幕
                    // 上滑动的时候。
                    Log.e("initSoftkeyAnima", "ime:" + insets.getInsets(WindowInsets.Type.ime()).top +
                            " " + insets.getInsets(WindowInsets.Type.ime()).bottom)

                    mBind.clParent.translationY =  -insets.getInsets(WindowInsets.Type.ime()).bottom.toFloat()

                    Log.d("TAG", "initSoftkeyAnima onProgress: ")
                    return insets
                }


                override fun onEnd(animation: WindowInsetsAnimation) {


                    // #5: 最后 onEnd 在动画已经结束的时候被调用。使用这个来
                    // 清理任何旧的状态。


                    Log.d("TAG", "initSoftkeyAnima onEnd: ")
                }

                override fun onApplyWindowInsets(
                    v: View?,
                    insets: WindowInsetsCompat?
                ): WindowInsetsCompat? {
                    Log.d("TAG", "initSoftkeyAnima onEnd: ")
                    return insets
                }
            }
            mBind.rootParent.setWindowInsetsAnimationCallback(cb)


//            val cb1 = object : WindowInsetsAnimationCompat.Callback(WindowInsets.Type.ime()),OnApplyWindowInsetsListener {
//
//
//                override fun onPrepare(animation: WindowInsetsAnimationCompat) {
//                    super.onPrepare(animation)
//                    Log.d(TAG, "initSoftkeyAnima1 onPrepare: ")
//                }
//
//                override fun onStart(
//                    animation: WindowInsetsAnimationCompat,
//                    bounds: WindowInsetsAnimationCompat.BoundsCompat
//                ): WindowInsetsAnimationCompat.BoundsCompat {
//                    Log.d(TAG, "initSoftkeyAnima1 onStart: ")
//
//                    return super.onStart(animation, bounds)
//                }
//
//                override fun onProgress(
//                    insets: WindowInsetsCompat,
//                    runningAnimations: List<WindowInsetsAnimationCompat>
//                ): WindowInsetsCompat {
//                    // onProgress() is called when any of the running animations progress...
//
//
//                    Log.d(TAG, "initSoftkeyAnima1 onProgress: ")
//                    return insets
//                }
//
//                override fun onEnd(animation: WindowInsetsAnimationCompat) {
//                    Log.d(TAG, "initSoftkeyAnima1 onEnd: ")
//                }
//
//                override fun onApplyWindowInsets(
//                    v: View?,
//                    insets: WindowInsetsCompat?
//                ): WindowInsetsCompat? {
//                    Log.d(TAG, "initSoftkeyAnima1 onApplyWindowInsets: ")
//                    return insets
//                }
//
//
//            }
//
//            ViewCompat.setWindowInsetsAnimationCallback(
//                mBind.edit,
//               cb1
//            )
//            ViewCompat.setOnApplyWindowInsetsListener( mBind.edit, cb)

        }
    }
}